import './index.scss'
import React, {useState} from "react";
import FormComtent, {FromListType} from "../../componets/FormComtent";
import {RuleObject} from "rc-field-form/lib/interface";
import {message, UploadFile} from "antd";
import {FormInstance} from "antd/es/form/hooks/useForm";
import {login, register} from "../../axios/request";
import {RegisterBodyType} from "../../axios/type";
import {useNavigate} from "react-router-dom";
import {AxiosResponse} from "axios";
import {ResponseType} from "../../axios";

const Login = () => {
    const [form, setForm] = useState<FormInstance<any>>();
    // 控制登录还是查询
    const [isLogin, setIsLogin] = useState<boolean>(true);
    // 头像上传状态设置
    const [avatarList, setAvatarList] = useState<UploadFile[]>([]);
    const n = useNavigate();
    // 勾选项内置组件
    const CheckComponent: () => JSX.Element = () => {
        return (
            <span className={isLogin ? 'no_account' : 'no_account yes_account'}
                  onClick={() => {
                      setIsLogin(v => !v);
                      form?.resetFields()
                  }}>{isLogin ? '没有账号？' : '已有账号？'}
            </span>
        )
    }
    // 登录表单列
    const formList = getFormList(CheckComponent);
    //注册表单列
    const registerFormList = getRegisterFormList(CheckComponent, avatarList, setAvatarList);
    // 完成事件
    const onFinish = (v: any) => {
        let data: RegisterBodyType;
        let request: Promise<any>;
        if (isLogin) {
            request = login(v);
        } else {
            data = {
                ...v,
                avatar_id: avatarList[0]?.response?.data?.id
            }
            request = register(data);
        }
        request.then((r: AxiosResponse<ResponseType>) => {
            if (r?.data?.code !== 1) return;
            message.success(isLogin ? "登录成功" : '注册成功');
            if (isLogin) {
                window.location.href = "/message";
            } else {
                setIsLogin(true);
            }
        });
    }
    return (
        <div className="login_box">
            {/*登录*/}
            <div className="login_inner">
                <h2>{isLogin ? '欢迎登录' : '欢迎注册'}</h2>
                <FormComtent formList={isLogin ? formList : registerFormList}
                             onFinish={onFinish}
                             configText={isLogin ? '登录' : '注册'}
                             btnStyle={{marginBottom: 0}}
                             isReset={true}
                             setForm={setForm}
                             className='login_form'
                />
            </div>
        </div>
    )
}

export default Login;

// 表单list
const getFormList = (CheckComponent: () => JSX.Element): Array<FromListType> => {
    return [
        {
            label: "账号",
            name: "username",
            type: "text",
            placeholder: "请输入账号",

            rules: [
                {
                    required: true,
                    message: "请输入账号"
                }
            ],
        },
        {
            label: "密码",
            name: "password",
            type: "password",
            placeholder: "请输入密码",
            formItemStyle: {
                marginBottom: 0
            },
            rules: [
                {
                    required: true,
                    message: "请输入密码"
                }
            ],
        },
        {
            label: "",
            name: "isAvoid",
            type: "checkbox",
            placeholder: "七天免登录",
            formItemStyle: {
                marginBottom: '0'
            },
            CheckComponent,
        },
    ]
}

// 注册
const getRegisterFormList = (RadioComponent: () => JSX.Element, fileList: UploadFile[], setFileList: any): Array<FromListType> => {
    return [
        {
            label: "头像",
            name: "avatar_id",
            type: "upload",
            fileList,
            setFileList,
            uploadStyleType: "picture-circle",
            rules: [
                {
                    requires: true,
                    message: "请上传头像"
                }
            ]
        },
        {
            label: "账号",
            name: "username",
            placeholder: "请输入账号",
            type: "text",
            rules: [
                {
                    required: true,
                    message: "请输入账号"
                }
            ]
        },
        {
            label: "邮箱",
            name: "email",
            placeholder: "请输入邮箱",
            type: "text",
            rules: [
                {
                    required: true,
                    message: "请输入邮箱"
                },
                {
                    required: true,
                    message: "邮箱格式不正确",
                    type: "email",
                }
            ]
        },
        {
            label: "密码",
            name: "password",
            placeholder: "请输入密码",
            type: "password",
            rules: [
                {
                    required: true,
                    message: "请输入密码"
                }
            ],
        },
        {
            label: "确认密码",
            name: "config_password",
            placeholder: "请再次确认密码",
            type: "password",
            formItemStyle: {
                marginBottom: '0'
            },
            rules: [
                {
                    required: true,
                    message: "请输入确认密码"
                },
                ({getFieldValue}: { getFieldValue: (v: string) => string }) => ({
                    // value代表当前选项输入的值
                    validator(_: RuleObject, value: string) {
                        if (!value || getFieldValue('password') === value) {
                            // 验证通过
                            return Promise.resolve()
                        }
                        return Promise.reject(new Error("两次输入的密码不一致"))
                    }
                })
            ],
        },
        {
            label: "性别",
            name: "sex",
            type: "radio",
            CheckComponent: RadioComponent,
            formItemStyle: {
                marginBottom: '0'
            },
            radioData: [
                {
                    value: 1,
                    label: "男"
                },
                {
                    value: 2,
                    label: "女"
                }
            ],
            rules: [
                {
                    required: true,
                    message: "请选择性别"
                }
            ]
        }
    ]
}
